import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.resps.Tuple;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RedisDemozset {
    public static void test1(Jedis jedis){
        System.out.println("zadd 和 zrange");
        jedis.flushAll();

        jedis.zadd("key",99,"kzf");
        Map<String,Double>map = new HashMap<>();
        map.put("whx",88.0);
        map.put("lyz",77.0);
        jedis.zadd("key",map);
        //这里考虑到zset有序性的特点，所以用List而不是Set，虽然也具有唯一性
        List<String> result = jedis.zrange("key",0,-1);
        System.out.println(result);
        List<Tuple> tuples = jedis.zrangeWithScores("key",0,-1);
        System.out.println(tuples);
        String member = tuples.get(0).getElement();
        Double score = tuples.get(0).getScore();
        System.out.println(member);
        System.out.println(score);

    }
    public static void test2(Jedis jedis){
        System.out.println("zcard:");
        jedis.flushAll();
        jedis.zadd("key",99,"kzf");
        jedis.zadd("key",88,"whx");
        jedis.zadd("key",77,"lyz");
        long len = jedis.zcard("key");
        System.out.println(len);
    }
    public static void test3(Jedis jedis){
        System.out.println("zrem:");
        jedis.flushAll();
        jedis.zadd("key",99,"kzf");
        jedis.zadd("key",88,"whx");
        jedis.zadd("key",77,"lyz");
        long result = jedis.zrem("key","whx");
        System.out.println(result);
        List<Tuple> tuples = jedis.zrangeWithScores("key",0,-1);
        System.out.println(tuples);
    }
    public static void test4(Jedis jedis){
        System.out.println("zscore:");
        jedis.flushAll();
        jedis.zadd("key",99,"kzf");
        jedis.zadd("key",88,"whx");
        jedis.zadd("key",77,"lyz");
        //这里的Double使用包装类，因为可能获取分数的member不存在
        //这时候就可以正常返回空值，而不是空指针异常
        Double score= jedis.zscore("key","whx");
        System.out.println(score);
        score = jedis.zscore("key","zzz");
        System.out.println(score);
    }
    public static void test5(Jedis jedis){
        System.out.println("zrank:");
        jedis.flushAll();
        jedis.zadd("key",99,"kzf");
        jedis.zadd("key",88,"whx");
        jedis.zadd("key",77,"lyz");
        //主要rank是从0开始的，不是1，zset默认按分数升序，同分数看member名的字典序
        Long rank = jedis.zrank("key","whx");
        System.out.println(rank);
    }
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("127.0.0.1", 8888);
        try (Jedis jedis = jedisPool.getResource()) {
            test5(jedis);
        }

    }
}
